package com.zsrt.devbase.common.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.zsrt.devbase.common.annotation.Token;
import com.zsrt.devbase.common.utils.ConstantDefine;

public class TokenInterceptor extends HandlerInterceptorAdapter{
	private Logger logger = Logger.getLogger(getClass().getName());
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (handler instanceof HandlerMethod) {//判断请求的方法
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();//获取请求所有的方法
			Token annotation = method.getAnnotation(Token. class );//获取注解的方法
			if (annotation != null ) {
				boolean needSaveSession = annotation.save();//查看注解是否移除token

				//需要保存session则在session中重新新建一个以token为键   UUID为值
				if (needSaveSession) {
					request.getSession( false ).setAttribute(request.getParameter("token") , UUID.randomUUID().toString());
				}
				boolean needRemoveSession = annotation.remove();//是否需要将token从session中移除
				if (needRemoveSession) {
					//是否重复提交
					if (isRepeatSubmit(request)) {
						//当重复提交时返回一个错误信息
						Map<String,Object> errorMap = new HashMap<String,Object>();
						errorMap.put(ConstantDefine.CHECK_ERROR, "系统正在处理。请勿重复提交！");
						response.setCharacterEncoding("UTF-8");
						response.setContentType("application/json; charset=utf-8");
						PrintWriter out = null; 
						try {  
							out = response.getWriter();  
							out.append(JSON.toJSONString(errorMap));  
							logger.debug("返回是\n");  
							logger.debug(JSON.toJSONString(errorMap));  
						} catch (IOException e) {  
							e.printStackTrace();  
						} finally {  
							if (out != null) {  
								out.close();  
							}  
						}
						return false ;
					}
					//将token从session中移除
					String clinetToken = request.getParameter(ConstantDefine.TOKEN);
					request.getSession( false ).removeAttribute(clinetToken);
				}
			}
			return true ;
		} else {
			//不需要生成token的就调用父类拦截器的方法
			return super .preHandle(request, response, handler);
		}
	}

	/**
	 * 判断是否重复提交
	 * @param request
	 * @return
	 */
	private boolean isRepeatSubmit(HttpServletRequest request) {
		String clinetToken = request.getParameter(ConstantDefine.TOKEN);//获取客户端的token
		String serverToken = (String) request.getSession( false ).getAttribute(clinetToken);//获取服务端的token
		if (serverToken == null ) {//如果为空   则为重复提交
			return true ;
		}
		if (clinetToken == null ) {//如果为空   则为重复提交
			return true ;
		}
		if (!serverToken.equals(clinetToken)) {//如果两个值不匹配   则为重复提交
			return true ;
		}
		return false ;
	}
	
}

